package db

import (
	"boy-go/pkg/config"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"os"
	"sync"
	"time"
)

var _dbs = make(map[string]*gorm.DB)
var _dbMu sync.RWMutex
var _configKey = "mysql"
var (
	Master = "master"
)

func InitDB(conf config.DatabaseConfig) {
	dsn := fmt.Sprintf("%s:%s@%s", conf.Username, conf.Password, conf.Url)

	// 设置 GORM 的日志级别为 Info，这样会打印出 SQL
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold: time.Second, // 慢 SQL 阈值
			LogLevel:      logger.Info, // 打印所有 SQL（包括 info 级别）
			Colorful:      true,        // 是否启用彩色打印
		},
	)

	database, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: newLogger,
	})
	if err != nil {
		panic("failed to connect database" + err.Error())
	}
	InitDefaultBatch(database)
}
func InitDefaultBatch(db *gorm.DB) {
	_dbs[Master] = db
}

func GetDBMust(key string) *gorm.DB {
	return _dbs[key]
}

func GetMasterDB() *gorm.DB {
	return _dbs[Master]
}
